from django.shortcuts import render,redirect
from django.http import HttpResponse, JsonResponse
from django.contrib import auth
from django.contrib.auth.models import User
import re
from django.contrib.auth.decorators import login_required
from . import models
from django.core import signing
import hashlib
from django.contrib.auth.hashers import check_password
import time
# Create your views here.


HEADER={
    'type':'JWT',
    'alg':'HS256'
}

def Encrypt(value):
    data=signing.dumps(value)
    data=signing.b64_encode(data.encode()).decode()
    return data

def Decrypt(value):
    data=signing.b64_decode(value.encode()).decode()
    data=signing.loads(data)
    return data

def Token(headers,payloads):
    header=Encrypt(headers)
    payload=Encrypt(payloads)
    md5=hashlib.md5()
    md5.update(("%s.%s"%(header,payload)).encode())
    signature=md5.hexdigest()
    token="%s.%s.%s"%(header,payload,signature)
    return token


def index(request):
    return render(request,'dormitory/index.html')

def register(request):
    return render(request,'dormitory/register.html')

def register_action(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')

        username = re.compile(r"^[a-zA-Z0-9]\w{6,18}")
        password = re.compile(r"^[a-zA-Z0-9]\w{6,18}")

        if username.match(user) and password.match(pwd):
            #person = User.objects.get(username = user)
            #if any(person):
                #return HttpResponse("<a href='register/'>用户名已存在，点击重新注册</a>")
            right_user = User.objects.create_user(username = user,password = pwd)
            return HttpResponse("<a href = '/app/login/'>注册成功，点击登录</a>")
        else:
            return HttpResponse("<a href='/app/register/'>用户名或密码不合法，请重新注册</a>")
    return render(request,'dormitory/register.html')

def loginn(request):
    return render(request,'dormitory/login.html')

def login_action(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        username = re.compile(r"^[a-zA-Z0-9]\w{6,18}")
        password = re.compile(r"^[a-zA-Z0-9]\w{6,18}")

        if username.match(user) and password.match(pwd):
            right_user = auth.authenticate(username=user, password=pwd)
            if right_user:
                auth.login(request,right_user)
                return redirect('/app/main/')
            else:
                return HttpResponse("<a href='/app/login/'>用户名或密码不合法，请重新登陆</a>")
        else:
            return HttpResponse("<a href='/app/login/'>用户名或密码不合法，请重新登陆</a>")

def login_action_token(request):
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    right_user = auth.authenticate(username=user, password=pwd)
    if right_user:
        headers = HEADER
        payloads = {'iss': right_user.username, 'iat': time.time()}
        token = Token(headers,payloads)
        info = {"token":token}
        info['code'] = 200
        return JsonResponse(info)   #这里直接返回jwt到页面，但是前端并无逻辑存储，可以学学JS再来存储。
    else:
        return HttpResponse('400')


@login_required
def main(request):
    dor_list = models.dormitory_nu.objects.all()
    return render(request,"dormitory/main.html",{"dor_list":dor_list})
